package com.ifast.sys.controller;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ifast.common.utils.FileUtil;
import com.ifast.common.utils.MD5;
import com.ifast.sys.service.UnitBasicinfoService;
import com.ifast.sys.util.PermissUtil;
import com.ifast.sys.util.PrivContent;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.AdminBaseController;
import com.ifast.common.utils.Result;
import com.ifast.sys.domain.RoleDO;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.RoleService;
import com.ifast.sys.service.UserService;
import com.ifast.sys.vo.UserVO;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * <pre>
 * </pre>
 * 
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/sys/user")
@Controller
public class UserController extends AdminBaseController {
    private String prefix = "sys/user";

    @Value("${photo.upload}")
    private String upload ;

    @Autowired
    UserService sysUserService;

    @Autowired
    RoleService roleService;

    @Autowired
    UnitBasicinfoService unitBasicinfoService;

    
    @Log("进入系统用户列表页面")
    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        Map resultMap =getSsqxAndSchMapByUserPriv(unitBasicinfoService);
        model.addAttribute("schMap", resultMap.get("schMap"));
        model.addAttribute("ssqxMap", resultMap.get("ssqxMap"));
        return prefix + "/user";
    }
    
    @Log("查询系统用户列表")
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<UserDO>> list(HttpServletRequest request) {
        String ssqxValue = request.getParameter("ssqxValue");
        String schValue = request.getParameter("schValue");
        String usertype = request.getParameter("usertype");
        String status = request.getParameter("userstatus");
        String searchName = request.getParameter("searchName");
        // 查询列表数据
        Wrapper<UserDO> wrapper = new EntityWrapper<UserDO>();
        wrapper.and("1=1");
        if(StringUtils.isNotBlank(usertype)){//用户类型不空
            wrapper.eq("usertype",usertype);
        }

        if(StringUtils.isNotBlank(status)){//用户状态不空
            wrapper.eq("status",status);
        }

        if(StringUtils.isNotBlank(searchName)){
            wrapper.like("concat(username,name,idcard)",searchName);//多字段模糊匹配
        }

        if(StringUtils.isNotBlank(ssqxValue)){//区县不空
        	wrapper.and("unitid in (select s.id from jyrc_unit_basicinfo s where s.ssqx={0})", ssqxValue);
        }

        if(StringUtils.isNotBlank(schValue)){//单位不空
            wrapper.eq("unitid",schValue);
        }

        /***校验用户范围权限****/
        if(PermissUtil.hasPermission(PrivContent.SM_SJPRIV)){//市级
            //do nothing
        }else if(PermissUtil.hasPermission(PrivContent.SM_QJPRIV)) {//区级
            if(!StringUtils.isNotBlank(ssqxValue)){//区县为空
            	wrapper.and("unitid in (select s.id from jyrc_unit_basicinfo s where s.ssqx={0})", getUser().getUnit().getSsqx());
            }
        }else if(PermissUtil.hasPermission(PrivContent.SM_XJPRIV)){//校级
            wrapper.eq("unitid",getUser().getUnitid());
        }else{
            wrapper.eq("unitid","autherror");
        }

        /******排序相关********/
        String sortName = request.getParameter("sortName");
        String sortOrder = request.getParameter("sortOrder");
        if(StringUtils.isNotBlank(sortName)){
            if("usertypeView".equals(sortName)){
                wrapper.orderBy("usertype","asc".equals(sortOrder));
            }else if("unitName".equals(sortName)){
                wrapper.orderBy("unitid","asc".equals(sortOrder));
            }else{
                wrapper.orderBy(sortName,"asc".equals(sortOrder));
            }
        }

        Page<UserDO> page = sysUserService.selectPage(getPage(UserDO.class), wrapper);

        for(UserDO u:page.getRecords()){//设置单位名称
            u.setUnitName(unitBasicinfoService.selectNameById(u.getUnitid()));
        }
        return Result.ok(page);
    }

    
    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        model.addAttribute("pageType", "save");
        model.addAttribute("user",new UserDO());
        // 单位列表
        Map resultMap =getSsqxAndSchMapByUserPriv(unitBasicinfoService);
        model.addAttribute("schMap", resultMap.get("schMap"));
        return prefix + "/edit";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("查看用户")
    @GetMapping("/look/{id}")
    String look(Model model, @PathVariable("id") Long id) {
        model.addAttribute("pageType", "look");

        UserDO userDO = sysUserService.selectById(id);
        model.addAttribute("user",userDO);
        // 单位列表
        Map resultMap =getSsqxAndSchMapByUserPriv(unitBasicinfoService);
        model.addAttribute("schMap", resultMap.get("schMap"));
        return prefix + "/edit";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        model.addAttribute("pageType", "update");
        UserDO userDO = sysUserService.selectById(id);
        model.addAttribute("user",userDO);
        // 单位列表
        Map resultMap =getSsqxAndSchMapByUserPriv(unitBasicinfoService);
        model.addAttribute("schMap", resultMap.get("schMap"));
        return prefix + "/edit";
    }


    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    Result<String> save(UserDO user) {
       if(StringUtils.isNotBlank(user.getIdcard())){
           Wrapper<UserDO> paramsWarp = new EntityWrapper<UserDO>();
           paramsWarp.where("idcard={0}", user.getIdcard());
           if (sysUserService.selectCount(paramsWarp) > 0) {
               return Result.build(Result.CODE_FAIL,"身份证号已存在");
           }else{
        		if (user.getIdcard().length() > 6) {
        			user.setPassword(MD5.MD5Encode(user.getIdcard().substring(user.getIdcard().length() - 6, user.getIdcard().length())));
        		} else {
        			user.setPassword(MD5.MD5Encode(user.getIdcard()));
        		}
           }
       }else{
    	   user.setPassword(MD5.MD5Encode("123456"));
       }

        if(StringUtils.isNotBlank(user.getUsername())){
            Wrapper<UserDO> paramsWarp = new EntityWrapper<UserDO>();
            paramsWarp.where("username={0}", user.getUsername());
            if (sysUserService.selectCount(paramsWarp) > 0) {
                return Result.build(Result.CODE_FAIL,"用户名已存在");
            }
        }

        user.setCreatetime(new Date());
        user.setUpdatetime(new Date());
        user.setOptperson(getUserId());
        sysUserService.insert(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("列表更新用户信息")
    @PostMapping("/update")
    @ResponseBody
    Result<String> update(UserDO user) {
        user.setUpdatetime(new Date());
        user.setOptperson(getUserId());
        sysUserService.updatePersonal(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新当前用户个人资料")
    @PostMapping("/updatePeronal")
    @ResponseBody
    Result<String> updatePeronal(UserDO user) {
        user.setId(getUserId());
        user.setUpdatetime(new Date());
        user.setOptperson(getUserId());
        sysUserService.updatePersonal(user);
        return Result.ok();
    }
    
    @Log("退出")
    @PostMapping("/exit")
    @ResponseBody
    boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !sysUserService.exit(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("当前用户更改密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    Result<String> resetPwd(UserVO userVO) {
        sysUserService.resetPwd(userVO, getUser());
        return Result.ok();
    }


    @Log("admin提交更改用户密码")
    @RequiresPermissions("sys:user:resetPwd")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    Result<String> adminResetPwd(UserVO userVO) {
        sysUserService.adminResetPwd(userVO);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:empower")
    @Log("用户角色设置")
    @GetMapping("/toempower/{id}")
    String toempower(Model model,@PathVariable("id") Long id) {
        UserDO userDO = sysUserService.selectById(id);
        model.addAttribute("user",userDO);
        List<RoleDO> roles = roleService.findListByUserId(id);
        model.addAttribute("roles", roles);
        return prefix + "/empower";
    }

    @RequiresPermissions("sys:user:empower")
    @Log("保存用户角色设置")
    @PostMapping("/empower")
    @ResponseBody
    Result<String> empower(UserDO user) {
        user.setUpdatetime(new Date());
        user.setOptperson(getUserId());
        sysUserService.updateById(user);
        return Result.ok();
    }

//    @Log("查询系统用户属性树形数据")
//    @GetMapping("/tree")
//    @ResponseBody
//    public Tree<DeptDO> tree() {
//        Tree<DeptDO> tree = new Tree<DeptDO>();
//        tree = sysUserService.getTree();
//        return tree;
//    }
    
//    @Log("进入系统用户树形显示页面")
//    @GetMapping("/treeView")
//    String treeView() {
//        return prefix + "/userTree";
//    }

//    @Log("上传头像")
//    @ResponseBody
//    @PostMapping("/uploadImg")
//    Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request)
//            throws Exception {
//        Map<String, Object> result = new HashMap<>();
//        result = sysUserService.updatePersonalImg(file, avatar_data, getUserId());
//        return Result.ok(result);
//    }
    
    @Log("进入个人中心")
    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = sysUserService.selectById(getUserId());
        model.addAttribute("user", userDO);
        return prefix + "/personal";
    }

    @Log("上传头像")
    @RequestMapping(value = "/uploadUserPhoto")
    void uploadUserPhoto(HttpServletRequest request, HttpServletResponse response, @RequestParam("file")MultipartFile mutiparFile) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            String  fileName = "";
            if (null != mutiparFile && !mutiparFile.isEmpty()) {
                fileName = mutiparFile.getOriginalFilename();
                String filePath = upload+"/tmp/";//文件上传临时路径
                fileName = getUserId()+FileUtil.getSuffix(fileName);
                File file = new File(filePath, fileName);
                if (!file.exists()) {
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();
                }
                mutiparFile.transferTo(file);
            }
            sb.append("true:"+fileName);
            sendHtml(response, sb.toString());
        }catch(Exception e) {
            e.printStackTrace();
            sendHtml(response, "false:上传失败");
        }
    }

    @RequestMapping(value = "/saveUserPhoto")
    public void  saveUserPhoto(HttpServletRequest request, HttpServletResponse response){
        StringBuffer sb = new StringBuffer();
        System.setProperty("java.awt.headless", "true");
        try{
            String photo = request.getParameter("photo");
            if (StringUtils.isNotBlank(photo)) {//上传了头像
                Integer x = Integer.parseInt(request.getParameter("x"));
                Integer y = Integer.parseInt(request.getParameter("y"));
                Integer w = Integer.parseInt(request.getParameter("w"));
                Integer h = Integer.parseInt(request.getParameter("h"));
                //根据图片名获取上传临时图片
                String filePath = upload+"/tmp/";
                File obfile = new File(filePath + photo);

                //检查上传头像文件夹是否存在不存在则创建
                File fold = new File(upload+"/upload/");
                if (!fold.exists()) {
                    fold.mkdirs();
                }

                //检查将要生成的头像是否存在  如果存在   删除文件
                String photoFilePath =upload+"/upload/"+photo;
                File userPhotoFile = new File(photoFilePath);
                if (userPhotoFile.exists()) {
                    userPhotoFile.delete();
                }

                //(根据裁剪参数重新生成图片)
                Thumbnails.of(obfile).sourceRegion(x, y, w , h).size(w, h).keepAspectRatio(false).toFile(userPhotoFile);

                //保存用户信息头像地址
                UserDO userDO = new UserDO();
                userDO.setId(getUserId());
                userDO.setPicLocation(photo);
                sysUserService.updatePersonal(userDO);

                //删除上传的临时文件
                if (obfile.exists()) {
                    obfile.delete();
                }
            }
            sb.append("{\"flag\":\"true\"}");
        } catch (Exception e) {
            sb.delete(0, sb.length());
            sb.append("{\"flag\":\"false\",\"msg\":\"操作失败,请更换一张图片!\"}");
        } finally {
            sendJson(response, sb);
        }
    }

    /**
     * IO流读取用户头像图片【没有设置默认】
     * @return
     */
    @RequestMapping(value = "/IoReadImage/upload", method = RequestMethod.GET)
    public void IoReadImage(String name,HttpServletRequest request,HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        BufferedInputStream bin =null;
        try {
            if (StringUtils.isBlank(name)) {
                name ="error.jpg";
            }
            //获取图片存放路径
            String imgPath = upload+"/upload/" + name;
            File userPhotoFile = new File(imgPath);
            if(!userPhotoFile.exists()){
                Resource resource = new ClassPathResource("/static/img/photo_s.jpg");
                bin = (BufferedInputStream)resource.getInputStream();
                response.setContentType("multipart/form-data");
                out = response.getOutputStream();
                //读取文件流
                int len = 0;
                byte[] buffer = new byte[1024 * 10];
                while ((len = bin.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            }else{
                ips = new FileInputStream(userPhotoFile);
                response.setContentType("multipart/form-data");
                out = response.getOutputStream();
                //读取文件流
                int len = 0;
                byte[] buffer = new byte[1024 * 10];
                while ((len = ips.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.close();
            if(ips!=null) {
                ips.close();
            }
            if(bin!=null){
                bin.close();
            }
        }
    }

    /**
     * IO流读取图片 by:long
     * @return
     */
    @RequestMapping(value = "/IoReadImage/tmp", method = RequestMethod.GET)
    public void IoReadImageTmp(String name,HttpServletRequest request,HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {
            if (StringUtils.isBlank(name)) {
                name ="error.jpg";
            }
            //获取图片存放路径
            String imgPath = upload+"/tmp/" + name;
            ips = new FileInputStream(new File(imgPath));
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.close();
            ips.close();
        }
    }

}
